package api

import (
	"FeedXmh/app/dao"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

var Func _func

type _func struct {

}

func (* _func)GET(r *ghttp.Request) {
	key := r.GetString("key")
	rid := r.GetString("rid")
	where := " 1=1 "
	if key != "" {
		where += " and concat(id,name,name_en) like '%" + key + "%' "
	}
	if rid != "" {
		where += fmt.Sprintf(" and id='%s'",rid)
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url,r.Method, userid) {
		res, err := db.Model("v_func").Where(where).OrderBy(" `level`,`order` ASC ").Select()
		if err != nil {
			g.Log().Line().Error(err)
		}
		r.Response.WriteJson(g.Map{
			"code":  0,
			"msg":   "",
			"count": len(res),
			"data":  res.List(),
		})
	} else {
		r.Response.WriteJson(g.Map{
			"code":  0,
			"msg":   "permission denied",
			"count": 0,
			"data":  nil,
		})
	}
	r.ExitAll()
}

func (* _func)PUT(r *ghttp.Request) {
	res := g.Map{
		"code": -1,
		"msg":  "保存失败",
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	var action_map = map[string]interface{}{}

	if params["action"] != nil {
		action_map = params["action"].(map[string]interface{})
		delete(params, "action")
	}
	//g.Dump(action_map)
	db:=g.DB(g.Cfg().GetString("custom.db_name"))

	url := r.URL.Path
	if dao.CheckApiPermission(url,r.Method, current_user) {
		if tx, err := db.Begin(); err == nil {
			_, err := tx.Model("t_func").Data(params).Where("id=?", params["id"]).Update()
			if err == nil {
				//清空全部action
				_, err = tx.Model("t_func_action").Where("func_id=?", params["id"]).Delete()
				if err == nil {
					//增加action
					list := gdb.List{}
					for k, _ := range action_map {
						item := gdb.Map{"action_id": k, "func_id": params["id"]}
						list = append(list, item)
					}
					if len(list) > 0 {
						_, err = tx.Model("t_func_action").Data(list).Insert()
						if err == nil {
							res["code"] = 1
							res["msg"] = "保存成功"
						}
					} else {
						res["code"] = 1
						res["msg"] = "保存成功"
					}

				}
			}

			if res["code"].(int) >= 0 {
				tx.Commit()
			} else {
				tx.Rollback()
			}
		}

	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (* _func)POST(r *ghttp.Request) {
	res := g.Map{
		"code": -1,
		"msg":  "保存失败",
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	var action_map = map[string]interface{}{}
	if params["action"] != nil {
		action_map = params["action"].(map[string]interface{})
		delete(params, "action")
	}

	url := r.URL.Path
	db:=g.DB(g.Cfg().GetString("custom.db_name"))

	if dao.CheckApiPermission(url,r.Method, current_user) {
		if tx, err := db.Begin(); err == nil {
			count, _ := tx.Model("t_func").Where("id=?", params["id"]).Count()
			if count > 0 {
				res["code"] = -1
				res["msg"] = "系统已经存在"
			} else {
				_, err := tx.Model("t_func").Data(params).Insert()
				if err == nil {
					//清空全部action
					_, err = tx.Model("t_func_action").Where("func_id=?", params["id"]).Delete()
					if err == nil {
						//增加action
						list := gdb.List{}
						for k, _ := range action_map {
							item := gdb.Map{"action_id": k, "func_id": params["id"]}
							list = append(list, item)
						}
						if len(list) > 0 {
							_, err = tx.Model("t_func_action").Data(list).Insert()
							if err == nil {
								res["code"] = 1
								res["msg"] = "保存成功"
							}
						} else {
							res["code"] = 1
							res["msg"] = "保存成功"
						}
					}
				}
			}

			if res["code"].(int) >= 0 {
				tx.Commit()
			} else {
				tx.Rollback()
			}
		}

	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (* _func)DELETE(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}
	id := r.GetString("rid")
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url,r.Method, current_user) {
		sqlres, _ := db.Model("t_func").Where("id=?", id).Delete()
		if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
			res["code"] = 1
			res["msg"] = "保存成功"
		} else {
			res["code"] = -1
			res["msg"] = "保存失败"
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
